import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ionicons/ionicons.dart';
import 'package:orginone/dart/base/storages/models/SubGroup.dart';
import 'package:orginone/components/PortalManagerWidget/navigation_event.dart';
import 'package:orginone/components/PortalManagerWidget/portalrefresh_event.dart';
import '../../dart/base/schema.dart';
import '../../dart/base/storages/hive_utils.dart';
import '../../main.dart';
import '../../utils/system/system_utils.dart';
import '../XDialogs/XDialog.dart';
import '../XImage/XImage.dart';
import '../XScaffold/XScaffold.dart';
import '../Tip/ToastUtils.dart';

class PortalManagerWidget extends StatefulWidget {
  const PortalManagerWidget({super.key});

  @override
  State<PortalManagerWidget> createState() => _PortalManagerState();
}

class _PortalManagerState extends State<PortalManagerWidget> {
  late SubGroup subGroup;
  var submenuIndex = 0;

  late TabController tabController;

  String tag = '';

  var tabIndex = 0;

  bool clickSave = false;

  var navigationItems = [];

  @override
  Widget build(BuildContext context) {
    _listen();
    subGroup = SubGroup();
    subGroup.type = "portal";
    subGroup.groups = [];
    subGroup.hidden = [];
    Group workbench = Group();
    workbench.value = "workbench";
    workbench.label = "工作台";
    workbench.allowEdit = false;
    subGroup.groups!.add(workbench);
    Group activity = Group();
    activity.value = "activity";
    activity.label = "动态";
    activity.allowEdit = false;
    subGroup.groups!.add(activity);
    navigationItems = (relationCtrl.user!.cacheObj.toString().indexOf("portalTemplate") < 0) ? [] : relationCtrl.user!.cacheObj.getValue("portalTemplate");
    if (navigationItems.isNotEmpty) {
      for (var value in navigationItems) {
        // 添加模板
        Group group = Group();
        group.value = value['type'];
        group.label = value['name'];
        group.allowEdit = true;
        subGroup.groups!.add(group);
      }
    }
    return XScaffold(
      titleName: "门户页面管理",
      centerTitle: true,
      titleSpacing: 75,
      leadingWidth: 50,
      leading: TextButton(
        onPressed: () {
          back();
        },
        child: Text(
          "取消",
          style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w500,
              fontSize: 21.sp),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            save();
            back();
            relationCtrl.user!.cacheObj.set("portalTemplate", navigationItems);
            portalRefreshEventBus.fire(PortalRefreshEvent(-1));
          },
          child: Text(
            "保存修改",
            style: TextStyle(fontSize: 21.sp),
          ),
        ),
      ],
      /**/
      body: ListView(
        physics: const NeverScrollableScrollPhysics(),
        children: [
          XDialog.headInfoWidget("", action: _rightIcon(XImage.portaltempAdd)),
          Container(
            height: 800,
            margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: BorderRadius.circular(15.w)),
            child: ReorderableListView.builder(
              shrinkWrap: true,
              itemBuilder: (context, index) {
                var item = subGroup.groups![index];
                return Container(
                  key: ValueKey(item.label),
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              color: Colors.grey.shade200, width: 0.5))),
                  child: ListTile(
                    leading: IconButton(
                      onPressed: () {
                        removeGroup(item);
                        if (navigationItems.isNotEmpty) {
                          navigationItems.forEach((element) async {
                            if (element['name'] == item.label) {
                              navigationItems.remove(element);
                            }
                          });
                        }
                        setState(() {});
                      },
                      icon: Icon(
                        Ionicons.remove_circle,
                        color:
                            (item.allowEdit ?? true) ? Colors.red : Colors.grey,
                      ),
                      padding: EdgeInsets.zero,
                      constraints: BoxConstraints(maxWidth: 30.w),
                    ),
                    trailing: Image.asset(
                      XImage.portalMenu,
                      fit: BoxFit.fill,
                      width: 8,
                      height: 14,
                    ),
                    title: Text(item.label!),
                    minLeadingWidth: 0,
                  ),
                );
              },
              itemCount: subGroup.groups!.length,
              onReorder: (int oldIndex, int newIndex) {
                changeGroupIndex(oldIndex, newIndex);
                // 假设我们要交换索引1和索引2的位置
                SystemUtils.swapEntities(
                    navigationItems, oldIndex - 2, newIndex - 2);
                setState(() {});
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 右侧 Icon
  Widget _rightIcon(dynamic path) {
    return Row(
      children: XImage.operationIcons([
        XImage.portaltempAdd,
      ]),
    );
  }

  //监听Bus events
  void _listen() {
    navigationEventBus.on<NavigationItem>().listen((event) {
      Group group = Group();
      group.value = event.type;
      group.label = event.name;
      group.allowEdit = true;
      Map<String, dynamic> mapData = {
        'key': event.key,
        'name': event.name,
        'type': event.type,
        'id': event.id,
        'tags': event.tags,
        'belongId': event.belongId,
        'metadata': event.metadata
      };
      // NavigationItem navigationItem = new NavigationItem(key: event.key, name: event.name, type: event.type, id: event.id, backgroundImageUrl: event.backgroundImageUrl, belongId: event.belongId);
      if (!navigationItems.toString().contains(event.name)) {
        navigationItems.add(mapData);
        addGroup(group);
      }
    });
  }

  void changeGroupIndex(int oldIndex, int newIndex) {
    var item = subGroup.groups?.removeAt(oldIndex);
    if (item?.value == "workbench" || item?.value == "activity") {
      subGroup.groups!.insert(oldIndex, item!);
      // subGroup.refresh();
      setState(() {});
      return;
    }

    int index = 0;

    if (newIndex < oldIndex) {
      index = newIndex;
    } else if (newIndex != 0) {
      index = newIndex - 1;
    }

    subGroup.groups!.insert(index, item!);
    // subGroup.refresh();
    setState(() {});
  }

  void save() {
    clickSave = true;
    HiveUtils.putSubGroup(subGroup.type ?? "portal", subGroup);
    ToastUtils.showMsg(msg: "保存成功");
  }

  void removeGroup(Group item) {
    if (!(item.allowEdit ?? true)) {
      ToastUtils.showMsg(msg: "此分组不允许移除");
      return;
    }
    subGroup.groups!.remove(item);
    subGroup.hidden!.add(item);
    // subGroup.refresh();
    setState(() {});
  }

  void addGroup(Group item) {
    subGroup.hidden!.remove(item);
    subGroup.groups!.add(item);
    // subGroup.refresh();
    setState(() {});
  }

  void back() {
    Navigator.pop(context, clickSave ? subGroup : null);
    // Get.back(result: clickSave ? subGroup : null);
  }
}

class FrequentlyUsed {
  String? id;
  String? name;
  dynamic avatar;

  FrequentlyUsed({this.id, this.name, this.avatar});
}
